package com.zxlfysj.sort;

import java.util.Arrays;

/**
 * 希尔排序
 * @author yangshujing
 * @create 2020-08-18 11:24
 */
public class ShellSort {
    public static void main(String[] args) {
        int[] arr = {1, 6, 7, 4, 3, 5, 8, 9, 0, 2};
        shellSort2(arr);
        System.out.println(Arrays.toString(arr));
    }

    //交换法
    public static void shellSort(int[] arr) {
        int temp = 0;
        for(int gap = arr.length / 2; gap > 0; gap /= 2) {
            for(int i = gap; i < arr.length; i++) {
                for(int j = i - gap; j >= 0; j -= gap) { //每组组内进行冒泡排序
                    if(arr[j] > arr[j + gap]) {
                        temp = arr[j];
                        arr[j] = arr[j + gap];
                        arr[j + gap] = temp;
                    }
                }
            }
        }
    }

    //移位法
    // int[] arr = {1, 6, 7, 4, 3, 5, 8, 9, 0, 2};
    public static void shellSort2(int[] arr) {
        for(int gap = arr.length / 2; gap > 0; gap /= 2) {
            for(int i = gap; i < arr.length; i++) {
               int j = i;
               int temp = arr[j];
               while( j - gap >= 0 && temp < arr[j - gap]) {
                   arr[j] = arr[j - gap];
                   j -= gap;
               }
               arr[j] = temp;
            }
        }
    }
}
